<template>
  <div class="announcement-container">
    <van-search
      v-model="objs.newsTitle"
      show-action
      placeholder="请输入搜索关键词"
      @search="onSearch"
    >
      <template #action>
        <div @click="onClickButton">搜索</div>
      </template>
    </van-search>

    <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
      <van-list
        v-model:loading="loading"
        :finished="finished"
        finished-text="没有更多了"
        @load="onLoad"
      >
        <List v-for="(item, index) in list" :key="index" :item></List>
      </van-list>
    </van-pull-refresh>
  </div>
</template>

<script lang="ts" setup>
import List from './components/List.vue'
import { ref } from 'vue'
import { getNewsList } from '@/services/user'

// 定义响应式数据
const list: any = ref([])
const loading = ref(false)
const finished = ref(false)
const refreshing = ref(false)

const objs = ref({
  pageNum: 1,
  pageSize: 5,
  newsTitle: '' // 绑定搜索标题
})

// 搜索功能
const onSearch = async () => {
  objs.value.pageNum = 1 // 重置页码
  list.value = [] // 清空当前列表
  finished.value = false // 重置加载完成状态
  loading.value = true // 开始加载
  await onLoad() // 调用加载函数执行搜索
}

const onClickButton = () => {
  onSearch() // 点击搜索按钮时调用搜索
}

// 加载列表数据
const onLoad = async () => {
  try {
    const res = await getNewsList(objs.value)
    list.value.push(...res.rows)
    //total这个是总条数
    if (objs.value.pageNum >= Math.ceil(res.total / objs.value.pageSize)) {
      finished.value = true
    } else {
      objs.value.pageNum++
    }
  } catch (error) {
    console.error('加载数据失败:', error)
  } finally {
    loading.value = false
    refreshing.value = false
  }
}

// 重新刷新列表
const onRefresh = () => {
  finished.value = false
  objs.value.pageNum = 1
  list.value = []
  loading.value = true
  onLoad()
}
</script>

<style lang="scss" scoped>
.announcement-container {
  padding-bottom: 57px;
  width: 100%;
  height: 100%;
  background: #f7f7f7;
  box-sizing: border-box;
}
</style>
